import { $post, $get, $delete } from "@/utils/request";
import router from "@/router";
import { useUserStore } from "@/stores/user";

// 登录
export const $Login = async (params: object) => {
    const { id, userpassword } = params
    try {
        await $post(`/user/login?id=${id}&userpassword=${userpassword}`)
        sessionStorage.setItem('id', id)
        router.push('/')
    } catch (err: any) {
        alert(err.message)
    }
}

//注册
export const $Register = async (params: object) => {
    const { name, userpassword } = params
    try {
        let ret = await $post(`/user/register?name=${name}&userpassword=${userpassword}`);
        alert(`账号：${ret.data.id}\n密码：${ret.data.userpassword}`)
    } catch (err: any) {
        alert(err.message)
    }
}

//获取用户信息
export const $LoginId = async (params: object) => {
    const { id } = params
    return await $post(`/user/loginss?id=${id}`);
}

//更新用户信息
export const $UpdateUser = async (params: object) => {
    try {
        return await $post('/user/update', params);
        // alert("更新成功")
    } catch (err: any) {
        alert(err.message)
    }
}

//修改用户密码接口
export const $UpdatePassword = async (params: object) => {
    const { id, userpassword, newuserpassword, newPassword } = params
    try {
        await $post(`/user/updatepassword?id=${id}&userpassword=${userpassword}&newuserpassword=${newuserpassword}&newPassword=${newPassword}`);
        alert("修改成功")
    } catch (err: any) {
        alert(err.message)
    }
}

//取消预约
export const $Cancel = async (params: object) => {
    const { id } = params
    await $post(`/user/Deletebooking?id=${id}`)
}

//预约医生
export const $Booking = async (params: object) => {
    const { id, doctorid, week, day } = params
    try {
        await $post(`/user/addbooking?id=${id}&doctorID=${doctorid}&week=${week}&day=${day}`);
        alert("预约成功")
    } catch (err: any) {
        alert(err.message)
    }
}

// 获取所有用户信息
export const $AllUser = async () => {
    return await $get('/abmin/getUser')
}

// 新增用户信息
export const $InsertUser = async (params: object) => {
    const { name, userpassword, phone, email, sex, address } = params
    return await $post(`/user/insertUser?name=${name}&userpassword=${userpassword}&phone=${phone}&email=${email}&sex=${sex}&address=${address}`)
}

// 删除用户信息
export const $DeleteUser = async (params: object) => {
    const queryParams = params.map(id => `ids=${id}`).join('&');
    return await $delete(`/user/deleteUser?${queryParams}`)
}